<template>
    <div>
              <!-- 新增/修改项目组表单 -->
        <el-dialog
            :close-on-click-modal = "false"
            ref = "dialog"
            v-dialogDrag
            class="posClass"
            width="720px"
            :before-close = "beforeClose"
            :visible.sync="isAddProGroupDiaVisible"
            center>
            <el-tabs type="border-card"  v-model="currTabValue">
                <el-tab-pane :label="title" :name="title">
                    <el-form ref="form" :model="form" :rules="rules" class="paddLR20 marT10" :inline="true" label-width = "110px">
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="项目组名称" prop = "groupName">
                                    <el-input v-model.trim="form.groupName" class="inputTxtWrapper" maxlength="50" placeholder="项目组名称"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="项目经理" prop = "groupLiableUserId">
                                    <el-select class="inputTxtWrapper" v-model="form.groupLiableUserId" placeholder="请选择项目负责人" @change = "handleSelect">
                                        <el-option label="---" value=""></el-option>
                                        <el-option
                                        v-for="item in userList"
                                        :key="item.id"
                                        :label="item.user_name"
                                        :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="产品经理" prop = "productManagerUserId">
                                    <el-select class="inputTxtWrapper" v-model="form.productManagerUserId" placeholder="请选择项目负责人" @change = "handleSelect">
                                        <el-option label="---" value=""></el-option>
                                        <el-option
                                        v-for="item in userList"
                                        :key="item.id"
                                        :label="item.user_name"
                                        :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="项目人员" prop = "proUsersIdArr">
                                    <el-transfer 
                                        filterable
                                        :render-content="renderFunc"
                                        v-model="form.proUsersIdArr" 
                                        :titles="['未选', '已选']" 
                                        :data = "generateData" 
                                        class = "addProGroup selfElTransfer">
                                    </el-transfer>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="解散项目组"  v-if = "title === '修改项目组'" name = "解散项目组">
                    <el-form ref="dissForm" :model="dissForm" :rules="dissFormRules" class="paddLR20 marT10" :inline="true" label-width = "110px">
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="当前项目组">
                                    {{groupReadOnlyName}}
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="解散原因" prop = "reason">
                                    <el-input v-model.trim="dissForm.reason" class="inputTxtWrapper" maxlength="50" placeholder="请输入解散原因"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
            
            <span slot="footer" class="dialog-footer">
                <el-button @click.stop.native = "beforeClose">取消并关闭</el-button>
                <el-button type="primary" @click.stop.native="addProGroup" v-show="currTabValue !== '解散项目组'">确认</el-button>
                <el-button type="primary" @click.stop.native="dissProGroup" v-show = "title === '修改项目组' && currTabValue === '解散项目组'">确认解散</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import http from '@/assets/js/http'
import _g from '@/assets/js/global'
export default {
    mixins: [http],
    props:{
        currProGroupObj:{
            type:Object,
            default:null
        },
        isAddProGroupDiaVisible : {
            type : Boolean,
            required:true
        },
        userList : {
            type : Array,
            required : true
        },
        proAnalyId:{
            type:Object,
            default : null
        },
        title:{
            type:String,
            default : ''
        }
    },
    
    data(){

        let validateFun = (rule,value,callback) => {
            if(this.form.groupLiableUserId === '' && this.form.productManagerUserId === ''){
                return callback(new Error('产品经理或项目经理至少选择一个'))
            }
            callback()
        }

        return{
            form:{
                groupName : '',//..项目组名
                groupLiableUserId :'',//..项目经理id
                productManagerUserId :'',//..产品经理id
                proUsersIdArr : []//    项目人员集合数组
            },

            currTabValue : '',//    当前tab标签选中值

            groupReadOnlyName : '',//..项目组只读名称
            dissForm:{
                reason:'',//..解散原因
            },

            generateData : [],

            rules: {
                groupName : [
                    { required: true, message: '请输入项目组名称', trigger: 'blur' },
                ],
                groupLiableUserId : [
                    { validator: validateFun,trigger: 'change' },
                ],
                productManagerUserId : [
                    { validator: validateFun,trigger: 'change' },
                ],
                proUsersIdArr : [
                    { required: true, message: '请选择项目人员', trigger: 'change' },
                ],
            },

            /* 格式化穿梭框内容 */
            renderFunc(h, option){
                return  <span title={ option.label}>{ option.label}</span>;
            },
        }
    },
    watch: {
        userList(newVal,oldVal){
            const generateData = []

            const obj = this.currProGroupObj
            let isDisabled = false//    默认可选
            let structNameArr = []//..组织名字数组
console.log('obj = ',obj)
            for(let item of newVal){
                
                isDisabled = false
                structNameArr = []
                if(this.title === '新增项目组'){
                    // isDisabled = obj !== null && obj.liable_user_id ===  item.id ? true : false
                }else if('修改项目组'){
                    // if(obj.liable_group_user_id === item.id || obj.product_manager_user_id === item.id){//   如果匹配项目负责人id或产品经理人员id
                    //     isDisabled = true
                    // }else{
                    //     isDisabled = false
                    // }
                    for(let userObj of obj.pro_group_users){
                        if(userObj.user_type === 1 || userObj.user_type === 2 || userObj.user_type === 4){//   如果匹配项目负责人id或产品经理人员id
                        // if(userObj.user_type === 1 || userObj.user_type === 2){//   如果匹配项目负责人id或产品经理人员id
                            if(item.id === userObj.pro_user_id){
                                isDisabled = true
                                break
                            }
                        }
                    }
                }

                for(let structObj of item.infiniteLevelStructure){
                    structNameArr.push(structObj.label)
                }
                const structName = structNameArr.join('/')
                generateData.push({
                    key : item.id,
                    label : item.user_name + ' - ' + structName,
                    structName,
                    disabled : isDisabled
                })
            }
            this.generateData = generateData.slice()
        },
        title(newVal,oldVal){
            this.currTabValue = newVal
        },
        currProGroupObj(newVal,oldVal){
            const proUsersIdArr = []//  项目人员集合数组
            if(newVal !== null){//  修改项目组
                this.groupReadOnlyName = newVal.pro_group_name

                this.form.groupName = newVal.pro_group_name
                // this.form.groupLiableUserId = newVal.liable_group_user_id === null ? '' : newVal.liable_group_user_id
                // this.form.productManagerUserId = newVal.product_manager_user_id  === null ? '' : newVal.product_manager_user_id
                // this.form.groupLiableUserId = newVal.liable_group_user_id === null ? '' : newVal.liable_group_user_id
                // this.form.productManagerUserId = newVal.product_manager_user_id  === null ? '' : newVal.product_manager_user_id

                let arr = newVal.pro_group_users.filter((val) => val.user_type === 1)
                if(arr.length > 0){
                    this.form.groupLiableUserId = arr[0].pro_user_id
                }
                arr = newVal.pro_group_users.filter((val) => val.user_type === 2)
                if(arr.length > 0){
                    this.form.productManagerUserId = arr[0].pro_user_id
                }

                if(arr.length <= 0){
                    arr = newVal.pro_group_users.filter((val) => val.user_type === 4)// 如果即是项目经理又是产品经理
                    if(arr.length > 0){
                        this.form.groupLiableUserId = arr[0].pro_user_id
                        this.form.productManagerUserId = arr[0].pro_user_id
                    }
                }
                

                for(let item of newVal.pro_group_users){
                    if(item.user_type === 3){// 如果为普通项目组人员
                        proUsersIdArr.push(item.pro_user_id)
                    }
                }
                this.form.proUsersIdArr = proUsersIdArr.slice()
            }
        },
        deep:true
    },
    created () {
    },
    methods: {
        /* 关闭弹框 */
        beforeClose(str) {
            this.generateData = []

            this.$refs.form.resetFields();
            this.form.groupName = ''
            this.form.groupLiableUserId = ''
            this.form.productManagerUserId = ''
            this.form.proUsersIdArr = []

            this.dissForm.reason = ''

            this.groupReadOnlyName = ''
            this.$emit('hideAddOneProGroupDialog',str)
        },
         /* 项目负责人下拉框change事件 */
        handleSelect(){

            const generateData = this.generateData.slice()

            let proUsersIdArr = this.form.proUsersIdArr
            let groupLiableUserId = this.form.groupLiableUserId
            let productManagerUserId = this.form.productManagerUserId
            this.form.proUsersIdArr = proUsersIdArr.filter(userId => userId !== groupLiableUserId && userId !== productManagerUserId).slice()//  项目人员里面排除项目组负责人与产品经理

            generateData.forEach((item,index) => {
                // if(item.key === groupLiableUserId || item.key === this.currRowRecord.liable_user_id){//    如果左侧列表有项目组负责人或项目负责人
                if(item.key === groupLiableUserId || item.key === productManagerUserId){//    如果左侧列表有项目组负责人或项目负责人
                    item.disabled = true
                }else{
                    item.disabled = false
                }
            })
            this.generateData = generateData.slice()
        },
        /* 解散项目组 */
        dissProGroup(){
            const that = this
            const proGroupId = that.currProGroupObj.id//    所属项目组id
            const reason = that.dissForm.reason//   解散原因

            that.$confirm('是否确认解散?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(() => {
                _g.showLoading('提交中')
                that.apiPost('admin/task/dissProGroup', {proGroupId,reason}).then((res) => {
                    _g.showLoading().close()
                    if(typeof res === 'string'){
                        res = JSON.parse(res)
                    }
                    if (res.code != 200) {
                        that.handleError(res)
                    } else {
                        if(res.data.isSuccess === 0){             //  成功
                            _g.toastMsg("success", res.message)
                                that.beforeClose(that.title)
                        }else if(res.data.isSuccess === 1){
                            _g.toastMsg("error", res.message)
                        }
                    }
                })
            }).catch(() => {})
        },
        /* 新增 / 修改项目组 */
        addProGroup(){
            const that = this
            let url = ''//..请求地址
            let data = {}

            const proAnalyId = that.proAnalyId

            let proUsersIdArr = [] // 待新增项目人员id数组

            let currProGroupObj = this.currProGroupObj//    当前项目组信息

            // let delProGroupUsersIdsArr = []// 待删除项目人员id数组

            // let oldProGroupUsersIdArr = []// 原来的项目组人员id数组

            let isSame = false//    默认项目经理与产品经理不是同一个人

            if(that.title === '新增项目组'){
                url = 'admin/task/addProGroup'
                data = {
                    proAnalyId,
                    ...that.form
                }
            }else if(that.title === '修改项目组'){
                url = 'admin/task/editProGroup'

                // 原来的项目人员
                // oldProGroupUsersIdArr = currProGroupObj.pro_group_users.map((item) => {
                //     if(item.user_type === 3){// 如果为普通项目组人员
                //         return item.pro_user_id
                //     }
                // })
                // for(let item of currProGroupObj.pro_group_users){
                //     if(item.user_type === 3){
                //         oldProGroupUsersIdArr.push(item.pro_user_id)
                //     }
                // }
                // oldProGroupUsersIdArr = currProGroupObj.pro_group_users.map(item => item.pro_user_id)
                // console.log('oldProGroupUsersIdArr = ',oldProGroupUsersIdArr)
                // 待处理人员id数组
                // proUsersIdArr = that.form.proUsersIdArr.filter((val) => oldProGroupUsersIdArr.indexOf(val) === -1)
                // proUsersIdArr = that.form.proUsersIdArr

                // 需要加上产品经理与项目经理的信息
                for(let id of that.form.proUsersIdArr){
                    let str = ''
                    str += `o|${id}`
                    proUsersIdArr.push(str)
                }

                if(that.form.groupLiableUserId === that.form.productManagerUserId){//   如果项目经理与产品经理是同一个人
                    proUsersIdArr.push(`s|${that.form.groupLiableUserId}`)
                    isSame = true
                }else{
                    if(that.form.groupLiableUserId !== '' && that.form.productManagerUserId !== ''){
                        proUsersIdArr.push(`sa|${that.form.groupLiableUserId}`,`sb|${that.form.productManagerUserId}`)
                    }else if(that.form.groupLiableUserId !== ''){
                        proUsersIdArr.push(`sa|${that.form.groupLiableUserId}`)
                    }else if(that.form.productManagerUserId !== ''){
                        proUsersIdArr.push(`sa|${that.form.productManagerUserId}`)
                    }
                }


                // // 待删除项目人员id数组
                // delProGroupUsersIdsArr = oldProGroupUsersIdArr.filter((val) => that.form.proUsersIdArr.indexOf(val) === -1)
                data = {
                    proGroupId : currProGroupObj.id,//    所属项目组id
                    groupName : that.form.groupName,//   项目组名称
                    // groupLiableUserId : that.form.groupLiableUserId,//  产品经理id
                    // productManagerUserId : that.form.productManagerUserId,//  项目经理id
                    proUsersIdArr,
                    isSame
                    // delProGroupUsersIdsArr
                }
            }
            
            console.log('data = ',data)
            this.$refs.form.validate((valid) => {
                if(valid){
                    that.$confirm('是否确认?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                        center: true
                    }).then(() => {
                        _g.showLoading('提交中')
                        that.apiPost(url, data).then((res) => {
                            _g.showLoading().close()
                            if(typeof res === 'string'){
                                res = JSON.parse(res)
                            }
                            if (res.code != 200) {
                                that.handleError(res)
                            } else {
                                if(res.data.isSuccess === 0){             //  成功
                                    _g.toastMsg("success", res.message)
                                     that.beforeClose(that.title)
                                }else if(res.data.isSuccess === 1){
                                    _g.toastMsg("error", res.message)
                                }else if(res.data.isSuccess === 2){
                                    _g.toastMsg("warning", res.message)
                                }
                            }
                        })
                    }).catch(() => {})
                }
            })
        },
    },
}
</script>

<style lang="less" scoped>

</style>


